from django.contrib.auth.hashers import make_password
from django.shortcuts import render

# Create your views here.
from rest_framework import mixins, viewsets, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

from user_operation.models import Address
from user_operation.serializers import AddressSerializer, UpdatePasswordSerializer
from users.models import Users


class AddressView(ModelViewSet):
    """
    list:
        地址列表
    retrieve:
        地址详情
    update:
        修改地址
    create:
        增加地址
    destroy:
        删除地址
    """
    queryset = Address.objects.all()
    serializer_class = AddressSerializer

    def get_queryset(self):
        return Address.objects.filter(users=self.request.user)

class UpdatePasswordView(mixins.CreateModelMixin,
                         viewsets.GenericViewSet):
    """
        create
            修改密码
    """
    queryset = Users.objects.all()
    serializer_class = UpdatePasswordSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        users = Users.objects.get(id=request.user.id)
        users.password = make_password(serializer.validated_data['password'], None, 'pbkdf2_sha256')
        users.save()
        return Response({"msg": "修改密码成功", "status_code": 200}, status=status.HTTP_200_OK)


